package com.hpin.mlxteacher.child;

import android.animation.ObjectAnimator;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.hpin.mlxteacher.R;
import com.hpin.mlxteacher.adapter.SignHistoryAdapter;
import com.hpin.mlxteacher.base.BaseActivity;
import com.hpin.mlxteacher.bean.AttendanceResult;
import com.hpin.mlxteacher.utils.AbDateUtil;
import com.hpin.mlxteacher.utils.CommonUtils;
import com.hpin.mlxteacher.utils.Constant;
import com.hpin.mlxteacher.utils.HttpUtil;
import com.hpin.mlxteacher.utils.LogUtil;
import com.hpin.mlxteacher.widget.MyDatePicker;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

//import com.umeng.analytics.MobclickAgent;

//import com.hpin.mlxteacher.bean.People;

/**
 * 历史考勤页面
 * Created by Aaron on 2015/7/28.
 */
public class HistoryActivity extends BaseActivity {

    private GridView gv_child;
    private TextView tv_red_line;
    private int screenwidth;
    //当前显示的 是上午还是中午还是下午 的 角标
    private int currentMessageIndex;

    //上午中午还是下午
    private int signType;
    private TextView tv_am;
    private TextView tv_noon;
    private TextView tv_pm;
    private SignHistoryAdapter mAdapter;

    //当前展示的日期
    private String currDay;

    private List<AttendanceResult.AttendanceDetail> attendanceDetails;
    //实到多少人
    private TextView tv_act_people;
    //一共多少人
    private TextView total_people;
    private TextView tv_date_attendance;
    private TextView tv_date;
    private int signCount;
    private String lastChoose = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_history);

        currDay = AbDateUtil.getStringByFormat(new Date(), AbDateUtil.dateFormatYMD);

        initWidget();

    }

    private void initWidget() {
        ImageView iv_left = (ImageView) findViewById(R.id.iv_left);
        tv_date_attendance = (TextView) findViewById(R.id.tv_date_attendance);

        iv_left.setOnClickListener(this);
        tv_date_attendance.setOnClickListener(this);

        tv_am = (TextView) findViewById(R.id.tv_choose_left);
        tv_noon = (TextView) findViewById(R.id.tv_choose_middle);
        tv_pm = (TextView) findViewById(R.id.tv_choose_right);

        tv_am.setText(getResources().getString(R.string.am));
        tv_noon.setText(getResources().getString(R.string.noon));
        tv_pm.setText(getResources().getString(R.string.pm));

        gv_child = (GridView) findViewById(R.id.gv_child);

        tv_red_line = (TextView) findViewById(R.id.tv_red_line);

        tv_am.setOnClickListener(this);
        tv_noon.setOnClickListener(this);
        tv_pm.setOnClickListener(this);

        //日期
        tv_date = (TextView) findViewById(R.id.tv_date);

        Calendar now = Calendar.getInstance();
        String month = ((now.get(Calendar.MONTH) + 1) < 10) ? ("0" + (now.get(Calendar.MONTH) + 1)) : (((now.get(Calendar.MONTH) + 1)) + "");
        String day = now.get(Calendar.DAY_OF_MONTH) < 10 ? "0" + now.get(Calendar.DAY_OF_MONTH) : now.get(Calendar.DAY_OF_MONTH) + "";
        String today = now.get(Calendar.YEAR) + "年" + month + "月" + day + "日";

        LogUtil.e("TAG", "month===" + month);

//        String today = now.get(Calendar.YEAR) + "年" + (now.get(Calendar.MONTH) + 1) + "月" + now.get(Calendar.DAY_OF_MONTH) + "日";
        tv_date.setText(today);

        tv_date_attendance.setText(today);

        tv_act_people = (TextView) findViewById(R.id.tv_act_people);
        total_people = (TextView) findViewById(R.id.total_people);

        screenwidth = CommonUtils.getScreenSize(this)[0];

        //默认显示上午
        currentMessageIndex = 0;
        tv_am.setTextColor(getResources().getColor(R.color.red));

        attendanceDetails = new ArrayList<AttendanceResult.AttendanceDetail>();

        mAdapter = new SignHistoryAdapter(this, attendanceDetails, currentMessageIndex);

        gv_child.setAdapter(mAdapter);

        signType = 0;

        getAttendanceData(currDay);

        gv_child.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //进入个人考勤历史记录页面
                Intent intent = new Intent(HistoryActivity.this, SingleHistoryActivity.class);
                //姓名
                intent.putExtra("nickName", attendanceDetails.get(position).nickName);
                intent.putExtra("stuId", attendanceDetails.get(position).id);
                startActivity(intent);
            }
        });
    }

    /**
     * 获取签到信息
     */
    private void getAttendanceData(String day) {

        if (mAdapter != null)
            mAdapter.setType(signType);

        JSONObject j = new JSONObject();
        j.put("token", sp.getString(Constant.token, ""));
        j.put("day", day);
        j.put("classId", sp.getString(Constant.classId, ""));

//        attendanceBean.type = signType + "";//签到的时间 早中晚三次的 状态  0早上    1中午    2晚上
        HttpUtil.setPostRequest("正在获取签到信息", this, Constant.WEB_ROOT + Constant.CHECKLIST,
                j.toJSONString(), getClass().getName(), new HttpUtil.SuccessListener() {
                    @Override
                    public void setOnSuccessListener(String str) {

                        try {

                            AttendanceResult attendanceResult = JSONObject.parseObject(str, AttendanceResult.class);

                            if (attendanceResult.code == Constant.SUCCESS) {

                                attendanceDetails = attendanceResult.data;

                                //设置班级人数 和 实到人数
                                attendStudent();

                            } else {

                                showToast(Constant.showErrorMsg(attendanceResult.code, HistoryActivity.this));

                            }

                        } catch (Exception e) {
                            e.printStackTrace();
                            showToast(Constant.NODATA);
                        }

                    }
                }, null);

    }

    /**
     * 设置班级人数 和 实到人数
     */
    private void attendStudent() {

        if (attendanceDetails==null)
            return;

        //计算去哪办共有多少人以及实到多少人
        total_people.setText("全班" + attendanceDetails.size() + "人");

        signCount = 0;//置为0,防止重复添加
        switch (signType) {

            case 0://上午

                for (int i = 0; i < attendanceDetails.size(); i++) {

                    if (attendanceDetails.get(i).signM == 1) {

                        ++signCount;
                    }
                }

                break;

            case 1://中午

                for (int i = 0; i < attendanceDetails.size(); i++) {

                    if (attendanceDetails.get(i).signA == 1){
                        ++signCount;
                    }

                }

                break;

            case 2://下午

                for (int i = 0; i < attendanceDetails.size(); i++) {

                    if (attendanceDetails.get(i).signN == 1) {

                        ++signCount;
                    }
                }

                break;

        }

        //代码设置TextView设置部分文字为不同颜色效果
        tv_act_people.setText(Html.fromHtml("实到" + "<font color='#ff0000'>" + (signCount) + "</font>" + "人"));

        if (mAdapter!=null) {
            mAdapter.setDatas(attendanceDetails);
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void widgetClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left:
                finish();
                break;
            case R.id.tv_date_attendance://选择日期

                Calendar c = Calendar.getInstance();
                c.setTime(AbDateUtil.getDateByFormat(currDay, AbDateUtil.dateFormatYMD));

                new MyDatePicker(HistoryActivity.this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear,
                                          int dayOfMonth) {

//                        LogUtil.e("tag", "====onDateSet====");

                        String month = (monthOfYear + 1) < 10 ? "0" + (monthOfYear + 1) : (monthOfYear + 1) + "";
                        String day = dayOfMonth < 10 ? "0" + dayOfMonth : dayOfMonth + "";
                        currDay = year + "-" + month + "-" + day;

                        tv_date_attendance.setText(year + "年" + month + "月" + day + "日");
                        tv_date.setText(year + "年" + month + "月" + day + "日");

                        if (currDay.equals(lastChoose)) {
                            return;
                        } else {
                            lastChoose = currDay;
                        }

                        getAttendanceData(currDay);

                    }

                }, c.get(Calendar.YEAR), c.get(Calendar.MONTH),
                        c.get(Calendar.DAY_OF_MONTH)).show();

                break;
            case R.id.tv_choose_left://上午

                changeTextColor2Gray();
                tv_am.setTextColor(getResources().getColor(R.color.red));

                changeRedLine(currentMessageIndex, 0);

                signType = 0;
//                getAttendanceData(currDay);

                if (mAdapter!=null)
                    mAdapter.setType(0);
                attendStudent();

                break;

            case R.id.tv_choose_middle://中午

                changeTextColor2Gray();
                tv_noon.setTextColor(getResources().getColor(R.color.red));
                changeRedLine(currentMessageIndex, 1);

                signType = 1;
                if (mAdapter!=null)
                    mAdapter.setType(1);
                attendStudent();
//                getAttendanceData(currDay);

                break;

            case R.id.tv_choose_right://下午

                changeTextColor2Gray();
                tv_pm.setTextColor(getResources().getColor(R.color.red));
                changeRedLine(currentMessageIndex, 2);

                signType = 2;
                if (mAdapter!=null)
                    mAdapter.setType(2);
                attendStudent();
//                getAttendanceData(currDay);

                break;
        }
    }

    /**
     * 把字体颜色都变灰色
     */
    private void changeTextColor2Gray() {
        tv_am.setTextColor(getResources().getColor(R.color.black));
        tv_noon.setTextColor(getResources().getColor(R.color.black));
        tv_pm.setTextColor(getResources().getColor(R.color.black));
    }

    /**
     * 改变红线的位置
     *
     * @param currentIndex 当前红线在哪个位置
     * @param toIndex      到哪个位置
     */
    private void changeRedLine(int currentIndex, int toIndex) {

        ObjectAnimator anim = null;
        //获取当前控件的x距离
        float curTranslationX = tv_red_line.getTranslationX();

//        LogUtil.e("TAG", "curTranslationX==>" + curTranslationX);

        switch (currentIndex) {

            case 0:

                //当前在第一位置
                switch (toIndex) {

                    case 1:

                        anim = ObjectAnimator.ofFloat(tv_red_line, "translationX", curTranslationX, screenwidth / 3);
                        currentMessageIndex = 1;
                        break;

                    case 2:
                        anim = ObjectAnimator.ofFloat(tv_red_line, "translationX", curTranslationX, screenwidth / 3 * 2);
                        currentMessageIndex = 2;
                        break;
                }

                break;

            case 1:

                //当前在第二位置
                switch (toIndex) {

                    case 0:
                        anim = ObjectAnimator.ofFloat(tv_red_line, "translationX", curTranslationX, 0);
                        currentMessageIndex = 0;
                        break;

                    case 2:
                        anim = ObjectAnimator.ofFloat(tv_red_line, "translationX", curTranslationX, screenwidth / 3 * 2);
                        currentMessageIndex = 2;
                        break;
                }

                break;

            case 2:

                //当前在第三位置
                switch (toIndex) {

                    case 0:
                        anim = ObjectAnimator.ofFloat(tv_red_line, "translationX", curTranslationX, 0);
                        currentMessageIndex = 0;
                        break;

                    case 1:
                        anim = ObjectAnimator.ofFloat(tv_red_line, "translationX", curTranslationX, screenwidth / 3);
                        currentMessageIndex = 1;
                        break;
                }

                break;
        }

        if (anim != null) {
            //设置移动时间0.5秒s
            anim.setDuration(500);
            anim.start();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        mApplication.cancelPendingRequests(getClass().getName());
    }

//    public void onResume() {
//        super.onResume();
//        MobclickAgent.onResume(this);       //统计时长
//    }
//
//    public void onPause() {
//        super.onPause();
//        MobclickAgent.onPause(this);
//    }
}